package com.example.yoho.mvp.view.fragment;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.lib_core.mvp.view.BaseFragment;
import com.example.yoho.R;
import com.example.yoho.di.component.DaggerHomeComponent;
import com.example.yoho.di.moudles.HomeModules;
import com.example.yoho.domain.Domain_Url;
import com.example.yoho.mvp.contract.HomeContract;
import com.example.yoho.mvp.model.entity.BannerEntity;
import com.example.yoho.mvp.model.entity.HomeGoodsEntity;
import com.example.yoho.mvp.model.entity.RecommendEntity;
import com.example.yoho.mvp.model.entity.UpgradeEntity;
import com.example.yoho.mvp.presenter.HomePresenter;
import com.example.yoho.mvp.view.activity.AdveritActivity;
import com.example.yoho.mvp.view.activity.GoodsDetailsActivity;
import com.example.yoho.mvp.view.activity.UpgradeActivity;
import com.example.yoho.mvp.view.adapter.MyHomeAdapter;
import com.example.yoho.mvp.view.adapter.MyRecommendAdapter;
import com.example.yoho.utils.MyCustom;
import com.example.yoho.utils.MyGlide;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends BaseFragment<HomePresenter> implements View.OnClickListener, HomeContract.View {

    private ImageView openDrawers;
    private List<String> list_banner=new ArrayList<>();
    private List<HomeGoodsEntity.Values> list=new ArrayList<>();
    private List<CustomTabEntity> lists_entity=new ArrayList<>();
    private MyHomeAdapter adapter;
    private android.support.v7.widget.RecyclerView goodsRecyc;
    private com.jwenfeng.library.pulltorefresh.PullToRefreshLayout goodsPull;
    private Banner mybanner;
    private SlidingMenu slidingMenu;
    private android.widget.RelativeLayout rl;
    private android.widget.HorizontalScrollView hsvw;
    private CommonTabLayout recommondTab;
    private View view;
    private RecyclerView recyclerView_head;
    private MyRecommendAdapter myRecommendAdapter;
    private ArrayList<RecommendEntity.RecommendValues> recommendValuesArrayList=new ArrayList<>();
    private String name;
    private String url;
    private String statues;
    @Override
    public int bondLayout() {
        PackageManager packageManager = getActivity().getPackageManager();

        try {
            PackageInfo info = packageManager.getPackageInfo(getActivity().getPackageName(), 0);
            name= info.versionName;
            int num=info.versionCode;
            if (!name.equals(num)){
                final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setIcon(R.drawable.live_logo);
                builder.setTitle("发现新版本，请尽快安装!");
                builder.setMessage("有货新特性，新增加了购物车免费购买，修复了买东西无详情一系列的问题，更正了一些bug!");
                builder.setPositiveButton("前往安装", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(getContext(), UpgradeActivity.class);
                        startActivity(intent);
                    }
                });
                builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(getContext(), "下次再说", Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();

            }else {
                initView();
            }
            Toast.makeText(getContext(), ""+num, Toast.LENGTH_SHORT).show();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return R.layout.fragment_home;
    }
    @Override
    public void Inject() {
        DaggerHomeComponent.builder().homeModules(new HomeModules(this)).build().fragmentInject(this);
    }

    @Override
    public void initView() {
        rl = (RelativeLayout) findviewByIds(R.id.rl);

        hsvw = (HorizontalScrollView) findviewByIds(R.id.hsvw);

        recommondTab= (CommonTabLayout) findviewByIds(R.id.recommond_tab);

        openDrawers = (ImageView) findviewByIds(R.id.open_drawers);

        goodsRecyc = (RecyclerView) findviewByIds(R.id.goods_recyc);

        goodsPull = (PullToRefreshLayout) findviewByIds(R.id.goods_pull);



        openDrawers.setOnClickListener(this);

        slidingMenu = new SlidingMenu(getContext());

        slidingMenu.attachToActivity(getActivity(), SlidingMenu.SLIDING_CONTENT);//绑定到指定的Context



        View view = LayoutInflater.from(getContext()).inflate(R.layout.silde_item, null);


        slidingMenu.setMenu(view);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        slidingMenu.setBehindOffset(250);


        MygoodSPull();

        MyScrollContract();

    }

    private void MygoodSPull() {
        goodsPull.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {

                list.clear();
                adapter.notifyDataSetChanged();
                mPresenter.HomeRequestAll(1,1);
            }

            @Override
            public void loadMore() {
                mPresenter.HomeRequstLoad();
                goodsPull.finishLoadMore();
            }
        });
    }

    private void MyScrollContract() {
        goodsRecyc.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) goodsRecyc.getLayoutManager();
                int position = layoutManager.findFirstVisibleItemPosition();
                if (position == 0) {
                    View firstView = layoutManager.findViewByPosition(position);
                    int firstHeight = firstView.getHeight();
                    int scrollY = -firstView.getTop();
                    Log.i("ysk", "onScrolled: "+firstHeight);
                    Log.i("ysk", "onScrolled: "+scrollY);
                    Log.i("ysk", "onScrolled: "+dx);
                    Log.i("ysk", "onScrolled: "+dy);
                    float alpha

                            = (float) scrollY / firstHeight;
                    rl.setBackgroundColor(Color.argb((int) (alpha * 255), 0, 0, 0));
                    if (scrollY >= 974) {
                        hsvw.setVisibility(View.VISIBLE);
                    } else {
                        hsvw.setVisibility(View.GONE);
                    }
                } else {
                    rl.setBackgroundColor(Color.BLACK);
                    hsvw.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    @Override
    public void initData() {

        mPresenter.HomeRequestAll(1,1);

        adapter=new MyHomeAdapter(R.layout.home_item,list);
        jumpGoods();
        goodsRecyc.setAdapter(adapter);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);

        gridLayoutManager.setSpanSizeLookup(new SpanSizeLookup());

        goodsRecyc.setLayoutManager(gridLayoutManager);


    }

    //万能适配器点击事件
    private void jumpGoods() {
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getContext(), GoodsDetailsActivity.class);
                startActivity(intent);
            }
        });
    }


    @Override
    public void showBanner(final List<BannerEntity.Values> bannerEntities) {

        for (int i = 0; i < bannerEntities.size(); i++) {

            String recommend_url = bannerEntities.get(i).recommend_url;

            list_banner.add(Domain_Url.IMAGE_URL +recommend_url);

        }
        adapter.notifyDataSetChanged();

        view = LayoutInflater.from(getContext()).inflate(R.layout.list_banner, null);
        recyclerView_head=view.findViewById(R.id.homehead_recyc);

        mybanner=view.findViewById(R.id.banners);


        MyBannersImager();

        mybanner.setImages(list_banner);

        mybannerclick(bannerEntities);

        mybanner.start();


    }

    private void mybannerclick(final List<BannerEntity.Values> bannerEntities) {
        mybanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent(getContext(), AdveritActivity.class);
                intent.putExtra("url",bannerEntities.get(position).recommend_path);
                startActivity(intent);
            }
        });
    }


    private void MyBannersImager() {
        mybanner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                MyGlide.GlideAS(context,path,imageView);
            }
        });
    }

    @Override
    public void showRecommend(RecommendEntity recommendEntities) {
        CommonTabLayout commonTabLayout=view.findViewById(R.id.recommond_tab);

        List<RecommendEntity.CategoryBean> category = recommendEntities.getCategory();
        for (int i = 0; i < category.size(); i++) {

            lists_entity.add(new MyCustom(recommendEntities.getCategory().get(i).getCategory_name(),0,0));

        }
        commonTabLayout.setTabData((ArrayList<CustomTabEntity>) lists_entity);

        recommondTab.setTabData((ArrayList<CustomTabEntity>) lists_entity);

        recommendValuesArrayList.addAll(recommendEntities.getRecommend());

        myRecommendAdapter=new MyRecommendAdapter(R.layout.recound_item,recommendValuesArrayList);

        recyclerView_head.setAdapter(myRecommendAdapter);

        recyclerView_head.setLayoutManager(new GridLayoutManager(getContext(),3));

        if (adapter.getHeaderLayoutCount()==0)
        adapter.addHeaderView(view);
        adapter.notifyDataSetChanged();





    }


    @Override
    public void showGoods(List<HomeGoodsEntity.Values> homeGoodsEntities) {
        Log.e("ysk", "showGoods: "+homeGoodsEntities.toString() );
        list.addAll(homeGoodsEntities);
        adapter.notifyDataSetChanged();
        goodsPull.finishRefresh();
        goodsPull.finishLoadMore();
    }

    @Override
    public void showLoadGoods(List<HomeGoodsEntity.Values> homeGoodEntities) {
        list.addAll(homeGoodEntities);
        adapter.notifyDataSetChanged();
        goodsPull.finishRefresh();
        goodsPull.finishLoadMore();
    }

    @Override
    public void showUpgrade(UpgradeEntity entity) {

         url = entity.getUrl();


    }

    class SpanSizeLookup extends GridLayoutManager.SpanSizeLookup {

        @Override
        public int getSpanSize(int i) {
            if (i==0){
                return 2;
            }else{
                return 1;
            }
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.open_drawers:
                slidingMenu.setMode(SlidingMenu.LEFT);
                slidingMenu.showMenu();
                break;
        }
    }

}
